package com.ibm.risk.irmp.base.auth.rest;


import com.ibm.risk.irmp.base.auth.entity.SystemUser;
import com.ibm.risk.irmp.base.auth.entity.SystemUserBase;
import com.ibm.risk.irmp.base.auth.service.IMenuManagementService;
import com.ibm.risk.irmp.base.auth.service.IOrganizationService;
import com.ibm.risk.irmp.base.auth.service.IUserManagementService;
import com.ibm.risk.irmp.base.auth.vo.UserMenuTreeVo;
import com.ibm.risk.irmp.base.auth.vo.UserSaveVO;
import com.ibm.risk.irmp.base.auth.vo.UserSearchParam;
import com.ibm.risk.irmp.base.auth.vo.UserVO;
import com.ibm.risk.irmp.common.SystemConstants;
import com.ibm.risk.irmp.common.auth.AuthUtils;
import com.ibm.risk.irmp.common.auth.IUserService;
import com.ibm.risk.irmp.common.auth.vo.LoginUser;
import com.ibm.risk.irmp.common.auth.vo.OrgInfoTree;
import com.ibm.risk.irmp.common.auth.vo.RoleVo;
import com.ibm.risk.irmp.common.vo.PagedResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/v2/auth")
@Slf4j
public class UserController implements IUserService {

    @Autowired
    private IUserManagementService userManagementService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IMenuManagementService menuManagementService;


    @GetMapping(value = "/users/searchUser")
    public PagedResult<UserVO> searchUser(UserSearchParam params) {
        return userManagementService.searchUser(params);
    }

    @GetMapping(value = "/users/fin-branches/{bizBranchCode}")
    public PagedResult<SystemUserBase> searchUser(@PathVariable String bizBranchCode,
                                                  @RequestParam(required = false) String username,
                                              @RequestParam(required = false) Integer pageIndex,
                                              @RequestParam(required = false) Integer pageSize) {

        PagedResult<SystemUserBase> userObj = organizationService.getBizBranchUserList(bizBranchCode, username, pageIndex, pageSize);
        return userObj;
    }

    @GetMapping(value = "/users/mng-branches/{mngBranchCode}")
    public PagedResult<SystemUserBase> searchUserMng(@PathVariable String mngBranchCode,
                                                          @RequestParam(required = false) Integer pageIndex,
                                                          @RequestParam(required = false) Integer pageSize) {

        PagedResult<SystemUserBase> userObj = organizationService.getMngBranchUserList(mngBranchCode, pageIndex, pageSize);
        return userObj;
    }

    @GetMapping(value = "/user/loadOperation")
    public Map loadOperation() {
        HashMap reqJSON = new HashMap();
        //用户组
        //ArrayList groupList = groupManagementService.showGroup(PSystemGroupEntity.ENUM_GROUP_TYPE.USER_BRANCH.getCode());

        //账务机构
        List<OrgInfoTree> level1FinBranch = organizationService.getLevel1BizBranch(SystemConstants.CONS_FLAG_SOLO);
//        ArrayList finDataList = new ArrayList();
//
//        if (level1FinBranch != null && level1FinBranch.size() > 0) {
//            level1FinBranch.forEach(x -> {
//                if ("0".equals(String.valueOf(x.get("BELONG_LEVEL")))) {
//                    HashMap node = new HashMap();
//                    node.put("title", x.get("FIN_BRANCH_NAME") + "(" + x.get("FIN_BRANCH_CODE") + ")");
//                    node.put("key", x.get("FIN_BRANCH_CODE"));
//                    node.put("value", x.get("FIN_BRANCH_CODE"));
//                    node.put("isLeaf", false);
//
//                    ArrayList children = new ArrayList();
//                    level1FinBranch.forEach(y -> {
//                        if ("1".equals(String.valueOf(y.get("BELONG_LEVEL")))
//                                && !SystemConstants.HQ_BIZ_BRANCH_CODE.equals(String.valueOf(y.get("FIN_BRANCH_CODE")))) {
//                            HashMap child = new HashMap();
//                            child.put("title", y.get("FIN_BRANCH_NAME") + "(" + y.get("FIN_BRANCH_CODE") + ")");
//                            child.put("key", y.get("FIN_BRANCH_CODE"));
//                            child.put("value", y.get("FIN_BRANCH_CODE"));
//                            child.put("isLeaf", true);
//                            children.add(child);
//                        }
//                    });
//                    node.put("children", children);
//                    node.put("expanded", true);
//                    finDataList.add(node);
//                }
//            });
//        }

        //管理机构
        List<OrgInfoTree> level1MngBranch = organizationService.getLevel1MngBranch(SystemConstants.CONS_FLAG_SOLO);
//        ArrayList mngDataList = new ArrayList();
//        if (level1MngBranch != null && level1MngBranch.size() > 0) {
//            level1MngBranch.forEach(x -> {
//                if ("0".equals(String.valueOf(x.get("BELONG_LEVEL")))) {
//                    HashMap node = new HashMap();
//                    node.put("title", x.get("MNG_BRANCH_NAME") + "(" + x.get("MNG_BRANCH_CODE") + ")");
//                    node.put("key", x.get("MNG_BRANCH_CODE"));
//                    node.put("value", x.get("MNG_BRANCH_CODE"));
//                    node.put("isLeaf", false);
//
//                    ArrayList children = new ArrayList();
//                    level1MngBranch.forEach(y -> {
//                        if ("1".equals(String.valueOf(y.get("BELONG_LEVEL")))
//                                && !SystemConstants.HQ_MNG_BRANCH_CODE.equals(String.valueOf(y.get("MNG_BRANCH_CODE")))) {
//                            HashMap child = new HashMap();
//                            child.put("title", y.get("MNG_BRANCH_NAME") + "(" + y.get("MNG_BRANCH_CODE") + ")");
//                            child.put("key", y.get("MNG_BRANCH_CODE"));
//                            child.put("value", y.get("MNG_BRANCH_CODE"));
//                            child.put("isLeaf", true);
//                            children.add(child);
//                        }
//                    });
//
//                    node.put("children", children);
//                    node.put("expanded", true);
//                    mngDataList.add(node);
//                }
//            });
//        }

        //reqJSON.put("groupList", groupList);
        reqJSON.put("bizList", level1FinBranch);
        reqJSON.put("mngList", level1MngBranch);
        List<RoleVo> systemRoleList = userManagementService.showRole();
        //.stream()
        //ilter(x -> !x.getRoleCode().equalsIgnoreCase(SystemConstants.RISK_SUPER_ROLE)).collect(Collectors.toList());
        reqJSON.put("roleList", systemRoleList);

        return reqJSON;
    }


    @Override
    @GetMapping(value = "/login/users/{username}")
    public LoginUser loadUserByUsername(@PathVariable String username) {
        return userManagementService.loadUserByUsername(username);
    }

    @Override
    @GetMapping(value = "/login/users/sso/{ssoKey}")
    public LoginUser getUserByUserSSOKey(@PathVariable String ssoKey) {
        return userManagementService.getUserByUserSSOKey(ssoKey);
    }

    @PutMapping(value = "/user/updatePassword")
    public Boolean updatePassword(@RequestBody HashMap reqJSON) {
        String username = (String) reqJSON.get("username");
        String password = (String) reqJSON.get("password");
        return userManagementService.updatePassword(username, password);
    }

    @PostMapping(value = "/users/addUser")
    public Boolean addUser(@RequestBody UserSaveVO userSaveVO) {
        // 校验用户密码
//        String password = (String)reqJSON.get("USER_PASSWORD");
//        DataValidateUtil.checkPassword(password);
        return userManagementService.saveNewUser(userSaveVO.getUser(), userSaveVO.getBizBranchCode(),
                userSaveVO.getMngBranchCode(), userSaveVO.getRoleCodes());
    }

    @PostMapping(value = "/users")
    public Boolean saveUser(@RequestBody SystemUser user) {
        // 校验用户密码
//        String password = (String)reqJSON.get("USER_PASSWORD");
//        DataValidateUtil.checkPassword(password);
        return userManagementService.saveUser(user);
    }

    @PutMapping(value = "/users/updateUser")
    public Boolean updateUser(@RequestBody UserSaveVO userSaveVO) {
        return userManagementService.updateUser(userSaveVO.getUser(), userSaveVO.getBizBranchCode(),
                userSaveVO.getMngBranchCode(), userSaveVO.getRoleCodes());
    }

    @DeleteMapping(value = "/users/{userId}")
    public Boolean delUserById(@PathVariable String userId) {
        return userManagementService.deleteUser(userId);
    }

    /**
     * 根据 username 查找用户信息
     * @param username
     * @return UserVO
     */
    @GetMapping(value = "/users/{username}")
    public SystemUser getUserById(@PathVariable String username) {
        return userManagementService.getUserByUsername(username);
    }

    /**
     * 读取用户已授权访问的功能菜单
     */
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public Map userInfo() {
        HashMap result = new HashMap();

        //用户信息
        LoginUser user = AuthUtils.getLoginUser();
        result.put("user", user);

        // TODO
        List<UserMenuTreeVo> menus = menuManagementService.buildUserMenu(user.getUsername());
        result.put("menus", menus);

//        result.put("last", auth.getLastAccessedDateTime() == null ? (new Date()).getTime() : auth.getLastAccessedDateTime().getTime());

        return (result);
    }
}
